package com.zhuang.work0430.commons.shiro;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhuang.work0430.commons.util.ShiroUtils;
import com.zhuang.work0430.entity.User;
import com.zhuang.work0430.entity.UserType;
import com.zhuang.work0430.service.UserService;
import com.zhuang.work0430.service.UserTypeService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @className: MyShiroRealm
 * @description: 类描述：
 * @author: 作者jia
 * @date: 2021/4/23 15:27
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private UserTypeService userTypeService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();
        UserType userType = userTypeService.getById(user.getUserTypeId());
        Set<String> userTypes=new HashSet<>();
        userTypes.add(userType.getTypeName());
        simpleAuthorizationInfo.setRoles(userTypes);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String name = (String) token.getPrincipal();
        Wrapper wrapper = new QueryWrapper<>().eq("name", name);
        User user = userService.getOne(wrapper);
        if (user == null) {
            return null;
        }
        ;
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes(user.getName()),
                getName()
        );
        //验证成功开始踢人(清除缓存和Session)
        ShiroUtils.deleteCache(name, true);
        return info;
    }


}
